import { hiprint } from "vue-plugin-hiprint";
import { message } from "ant-design-vue";

// 初始化 hiprint
export const initHiprint = () => {
	hiprint.init();
};

// 定义纸张类型
export const paperTypes = [
	{ label: "A3 (297 × 420 mm)", value: "A3", width: 297, height: 420 },
	{ label: "A4 (210 × 297 mm)", value: "A4", width: 210, height: 297 },
	{ label: "A5 (148 × 210 mm)", value: "A5", width: 148, height: 210 },
	{ label: "B3 (353 × 500 mm)", value: "B3", width: 353, height: 500 },
	{ label: "B4 (250 × 353 mm)", value: "B4", width: 250, height: 353 },
	{ label: "B5 (176 × 250 mm)", value: "B5", width: 176, height: 250 },
	{ label: "自定义", value: "custom" }
];

// 默认模板元素
export const defaultElements = [
	{
		name: "文本",
		type: "text",
		options: {
			text: "文本内容",
			fontSize: 14,
			color: "#000000",
			textAlign: "left"
		}
	},
	{
		name: "表格",
		type: "table",
		options: {
			columns: [
				{ title: "列1", dataIndex: "col1" },
				{ title: "列2", dataIndex: "col2" }
			]
		}
	},
	{
		name: "图片",
		type: "image",
		options: {
			src: ""
		}
	}
];

// 创建打印模板
export const createPrintTemplate = (options: { paperType: string; customWidth?: number; customHeight?: number }) => {
	const { paperType, customWidth, customHeight } = options;

	let width = 210;
	let height = 297;

	if (paperType !== "custom") {
		const paper = paperTypes.find(item => item.value === paperType);
		if (paper) {
			width = Number(paper.width);
			height = Number(paper.height);
		}
	} else if (customWidth && customHeight) {
		width = customWidth;
		height = customHeight;
	}

	return new hiprint.PrintTemplate({
		template: {
			panels: [
				{
					width: width,
					height: height,
					paperFooter: height - 10,
					paperHeader: 10,
					printElements: []
				}
			]
		}
	});
};

// 导出设计器
export const getDesigner = (elementId: string) => {
	return new hiprint.PrintDesigner(elementId);
};

// 预览打印
export const previewPrint = (template: any, data?: any) => {
	if (!template) {
		message.warning("请先设计打印模板");
		return;
	}
	template.printPreview(data);
};

// 导出PDF
export const exportPdf = (template: any, data?: any) => {
	if (!template) {
		message.warning("请先设计打印模板");
		return;
	}
	template.toPdf(data);
};
